<template>
  <div class="app-container">
    <div class="query-box">
      <el-button type="primary" plain icon="el-icon-circle-plus-outline" size="small" class="mr10" @click="handleAdd">
        新增
      </el-button>
      <!--      <el-input v-model="query.mercName" size="small" placeholder="商户名字" class="list-query-input"></el-input>-->
      <!--      <el-input v-model="query.shopName" size="small" placeholder="店员名字" class="list-query-input"></el-input>-->
      <!--      <el-input v-model="query.orderId" size="small" placeholder="订单ID" class="list-query-input input-width-s"></el-input>-->
      <!--      <el-input v-model="query.orderNo" size="small" placeholder="订单号" class="list-query-input"></el-input>-->
      <!--      <el-date-picker v-model="pickTime" size="small" type="datetimerange" class="mr10" align="right" unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :picker-options="pickerOptions"></el-date-picker>-->
      <!--      <el-select v-model="query.status" placeholder="状态" size="small" class="list-query-select">-->
      <!--        <el-option label="请选择" value="">请选择</el-option>-->
      <!--        <el-option v-for="item in Object.keys(orderStatus)" :key="orderStatus[item]" :value="item" :label="orderStatus[item]"></el-option>-->
      <!--      </el-select>-->
      <!--      <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>-->
    </div>

    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="权限名称" :show-overflow-tooltip="true" width="250"></el-table-column>
      <el-table-column prop="code" label="编码" width="150"></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="60"></el-table-column>
      <el-table-column prop="href" label="路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="type" label="类型" :formatter="typeFormat" width="80"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改权限对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属系统" prop="systemCode">
              <el-select v-model="form.systemCode" placeholder="所属系统" @change="querySysName" style="display:block">
                <el-option v-for="item in Object.keys(sys)" :key="sys[item].code" :value="sys[item].code" :label="sys[item].name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入权限编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入权限名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级权限">
              <treeSelect
                v-model="form.parentCode"
                :options="authOptions"
                :normalizer="normalizer"
                :show-count="true"
                @change="queryParentName"
                placeholder="选择上级权限"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio v-for="item in Object.keys(authType)" :label="item">{{authType[item]}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.type != '4'" label="权限图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected"/>
                <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="后台地址">
              <el-input v-model="form.href" placeholder="请输入后台地址"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {auths, getAuth, saveAuth, delAuth, sys} from "@/api/api";
  import TreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import IconSelect from "@/components/IconSelect";
  export default {
    name: "Auth",
    components: {TreeSelect, IconSelect},
    data() {
      return {
        authType: window.authType,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 权限表格树数据
        list: [],
        // 权限树选项
        authOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 系统
        sys: [],
        // 查询参数
        queryParams: {
          menuName: undefined,
          visible: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          systemCode: [{required: true, message: "请选择所属系统", trigger: "change"}],
          type: [{required: true, message: "权限类型不能为空", trigger: "blur"}],
          name: [{required: true, message: "权限名称不能为空", trigger: "blur"}],
          code: [{required: true, message: "权限编码不能为空", trigger: "blur"}],
          href: [{required: true, message: "后台地址不能为空", trigger: "blur"}]
        }
      };
    },
    created() {
      this.getAuths();
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      /** 查询权限列表 */
      getAuths() {
        this.loading = true;
        auths("admin").then(response => {
          this.authOptions = this.list = response.data;
          this.loading = false;
        });
      },
      /** 转换权限数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.code,
          label: node.name,
          children: node.children
        };
      },
      /** 查询权限下拉树结构 */
      getTreeSelect() {
        // listMenu().then(response => {
        //   this.authOptions = this.list;
        // });
      },
      // 权限状态字典翻译
      typeFormat(row, column) {
        return window.authType[row.type]
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          type: undefined,
          parentCode: undefined,
          code: undefined,
          name: undefined,
          icon: undefined,
          sort: undefined,
          href: undefined,
        };
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getAuths();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // this.resetForm("queryForm");
        this.handleQuery();
      },
      // 获取下拉框的name
      querySysName(e) {
        let sysAttr = this.sys.filter((item)=>{
          return item.code === e
        });
        this.form.systemName = sysAttr[0].name
      },
      // 获取下拉框的name
      queryParentName(e) {
        let parentAttr = this.list.filter((item)=>{
          return item.code === e
        });
        this.form.parentName = parentAttr[0].name
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if(this.sys.length == 0) {
          sys().then(res => {
            this.sys = res.data
          })
        }
        this.getTreeSelect();
        if (row != null && row.code) {
          this.form.parentCode = row.code;
        } else {
          this.form.parentCode = undefined;
        }
        this.open = true;
        this.title = "添加权限";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeSelect();
        getAuth(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改权限【" + row.name + "】";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            saveAuth(this.form).then(response => {
              this.msgSuccess((this.form.id ? "编辑" : "新增") + "权限成功");
              this.open = false;
              this.getAuths();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delAuth(row.id);
        }).then(() => {
          this.getAuths();
          this.msgSuccess("删除成功");
        })
      }
    }
  };
</script>
